<template>
  <div class="dashboard-container">
    <el-row :gutter="24" class="dashboard-row-nowrap" style="margin-bottom: 24px; flex-wrap: nowrap; overflow-x: auto;" @click="testRowClick">
      <el-col :xs="24" :sm="12" :md="3" v-for="card in cards" :key="card.title" class="dashboard-col" @click="handleCardClick(card)" style="cursor:pointer;">
        <el-card class="dashboard-card">
          <div class="card-title">
            <span>{{ card.title }}</span>
            <i :class="card.icon" v-if="card.icon" style="float:right;color:#409EFF;"></i>
          </div>
          <div class="card-content" v-html="card.content"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card class="chart-card">
          <div slot="header">
            <span>收支趋势</span>
          </div>
          <div class="chart" ref="trendChart"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <div slot="header">
            <span>支出分类</span>
          </div>
          <div class="chart" ref="pieChart"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="table-row">
      <el-col :span="24">
        <el-card>
          <div slot="header">
            <span>最近交易</span>
          </div>
          <el-table :data="recentTransactions" style="width: 100%">
            <el-table-column prop="date" label="日期" width="180"></el-table-column>
            <el-table-column prop="type" label="类型" width="100">
              <template slot-scope="scope">
                <el-tag :type="scope.row.type === '收入' ? 'success' : 'danger'">
                  {{ scope.row.type }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="category" label="分类" width="120"></el-table-column>
            <el-table-column prop="amount" label="金额" width="120">
              <template slot-scope="scope">
                <span :class="scope.row.type === '收入' ? 'income' : 'expense'">
                  {{ scope.row.type === '收入' ? '+' : '-' }}¥{{ scope.row.amount }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="description" label="描述"></el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  name: 'Dashboard',
  data() {
    return {
      totalIncome: 0,
      totalExpense: 0,
      balance: 0,
      monthlyBalance: 0,
      recentTransactions: [],
      trendChart: null,
      pieChart: null,
      loading: true,
      todoCount: 0,
      todayScheduleCount: 0,
      monthStat: { noteDone: 0, noteTodo: 0, scheduleDone: 0, scheduleTodo: 0 },
      cards: []
    }
  },
  mounted() {
    this.fetchDashboardData()
    this.initCharts()
  },
  methods: {
    async fetchDashboardData() {
      try {
        const response = await this.$http.get('/dashboard/summary')
        if (response.data.code === 20000) {
          const data = response.data.data
          this.totalIncome = data.totalIncome || 0
          this.totalExpense = data.totalExpense || 0
          this.balance = data.balance || 0
          this.monthlyBalance = data.monthlyBalance || 0
          this.recentTransactions = data.recentTransactions || []
          this.todoCount = data.todoCount || 0
          this.todayScheduleCount = data.todayScheduleCount || 0
          this.monthStat = data.monthStat || { noteDone: 0, noteTodo: 0, scheduleDone: 0, scheduleTodo: 0 }

          // 卡片数据
          this.cards = [
            { title: '我的待办', content: `<span class='main-num'>${this.todoCount}</span> 项`, icon: 'el-icon-edit-outline', route: '/memo' },
            { title: '今日日程', content: `<span class='main-num'>${this.todayScheduleCount}</span> 项`, icon: 'el-icon-date', route: '/schedule' },
            { title: '本月统计', content: `
              <div class='stat'>
                <span class='stat-done'>完成 <b class='stat-num'>${this.monthStat.noteDone + this.monthStat.scheduleDone}</b></span>
                <span class='stat-undone'>未完成 <b class='stat-num'>${this.monthStat.noteTodo + this.monthStat.scheduleTodo}</b></span>
              </div>
            `, icon: 'el-icon-s-data', route: '/dashboard' },
            { title: '总收入', content: `<span class='main-num'>￥${this.totalIncome}</span> 元`, icon: 'el-icon-money', route: '/bill' },
            { title: '总支出', content: `<span class='main-num'>￥${this.totalExpense}</span> 元`, icon: 'el-icon-shopping-cart-full', route: '/bill' },
            { title: '结余', content: `<span class='main-num'>￥${this.balance}</span> 元`, icon: 'el-icon-wallet', route: '/bill' },
            { title: '本月收支', content: `<span class='main-num'>￥${this.monthlyBalance}</span> 元`, icon: 'el-icon-date', route: '/bill' }
          ]

          // 更新图表数据
          if (data.trendData && data.expenseByCategory) {
            this.updateCharts(data.trendData, data.expenseByCategory)
          }
        } else {
          throw new Error(response.data.message || '获取数据失败')
        }
        this.loading = false
      } catch (error) {
        console.error('Dashboard data fetch error:', error)
        this.$message.error('获取数据失败')
        this.loading = false
      }
    },
    initCharts() {
      this.trendChart = echarts.init(this.$refs.trendChart)
      this.pieChart = echarts.init(this.$refs.pieChart)
      window.addEventListener('resize', () => {
        this.trendChart.resize()
        this.pieChart.resize()
      })
    },
    updateCharts(trendData, expenseByCategory) {
      // 收支趋势图配置
      const trendOption = {
        tooltip: {
          trigger: 'axis',
          formatter: '{b}<br/>{a0}: ¥{c0}<br/>{a1}: ¥{c1}'
        },
        legend: {
          data: ['收入', '支出']
        },
        xAxis: {
          type: 'category',
          data: trendData.map(item => item.month)
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: '¥{value}'
          }
        },
        series: [
          {
            name: '收入',
            type: 'line',
            data: trendData.map(item => item.income),
            itemStyle: {
              color: '#67C23A'
            }
          },
          {
            name: '支出',
            type: 'line',
            data: trendData.map(item => item.expense),
            itemStyle: {
              color: '#F56C6C'
            }
          }
        ]
      }

      // 支出分类饼图配置
      const pieData = Object.entries(expenseByCategory).map(([category, amount]) => ({
        name: category,
        value: amount
      }))

      const pieOption = {
        tooltip: {
          trigger: 'item',
          formatter: '{b}: ¥{c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 10,
          data: pieData.map(item => item.name)
        },
        series: [
          {
            name: '支出分类',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '30',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: pieData
          }
        ]
      }

      this.trendChart.setOption(trendOption)
      this.pieChart.setOption(pieOption)
    },
    handleCardClick(card) {
      console.log('card:', card, 'this.$router:', this.$router)
      if (card.route && this.$router) {
        this.$router.push(card.route)
      }
    },
    testRowClick(e) {
      console.log('el-row clicked', e)
    }
  }
}
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
}

.card-container {
  margin-bottom: 20px;
}

.card {
  transition: all 0.3s ease;
  cursor: pointer;
}

.card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.card-header i {
  font-size: 20px;
  margin-right: 10px;
}

.card-header h3 {
  margin: 0;
  font-size: 16px;
}

.card-content {
  text-align: center;
}

.card-content .number {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 5px;
}

.card-content .label {
  font-size: 14px;
  color: #666;
}

/* 弹窗动画 */
.el-dialog {
  transition: all 0.3s ease;
}

.el-dialog__wrapper {
  transition: all 0.3s ease;
}

/* 表格动画 */
.el-table__row {
  transition: all 0.3s ease;
}

.el-table__row:hover {
  background-color: #f5f7fa;
}

.data-card {
  height: 120px;
  margin-bottom: 20px;
}

.data-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.data-header .title {
  font-size: 16px;
  color: #606266;
}

.data-header i {
  font-size: 24px;
  color: #409EFF;
}

.data-content {
  text-align: center;
}

.amount {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.unit {
  font-size: 14px;
  color: #909399;
  margin-left: 5px;
}

.chart-row {
  margin-bottom: 20px;
}

.chart-card {
  height: 400px;
}

.chart {
  height: 350px;
}

.income {
  color: #67C23A;
}

.expense {
  color: #F56C6C;
}

.dashboard-row-nowrap {
  flex-wrap: nowrap !important;
  overflow-x: auto;
  margin-bottom: 24px;
  display: flex;
  justify-content: center;
}

.dashboard-col {
  min-width: 220px;
  flex: 1 1 0;
  max-width: 100%;
}

.dashboard-card {
  min-height: 110px;
  border-radius: 12px;
  box-shadow: 0 2px 8px #f0f1f2;
  margin-bottom: 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  transition: box-shadow 0.2s, border-color 0.2s;
}

.dashboard-card:hover {
  box-shadow: 0 4px 16px #d0e6ff;
  border-color: #409EFF;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 12px;
  color: #333;
}

.card-content {
  font-size: 22px;
  font-weight: bold;
  color: #222;
  text-align: center;
}

.main-num {
  font-size: 28px;
  color: #409EFF;
  font-weight: bold;
  margin-right: 4px;
}

.stat {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.stat-done {
  color: #67C23A;
  font-size: 16px;
}

.stat-undone {
  color: #F56C6C;
  font-size: 16px;
}

.stat-num {
  font-size: 24px;
  font-weight: bold;
  margin-left: 2px;
}
</style> 